<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <title>TCP示例</title>
  </head>
  <body>
    <h1>WebSocket 示例（TCP服务器为本地127.0.0.1:5000）</h1>
    <button onclick="connectWebSocket()">连接服务器</button>
    <button onclick="sendMessage()">发送消息(默认字符串:HelloWorld)</button>

    <script>
      let ws = null; // 全局WebSocket对象

      function showMessage() {
        alert("Hello World");
      }

      function connectWebSocket() {
        // www.javascriptcn.com code example
        ws = new WebSocket("ws://127.0.0.1:5000");
        //ws = new WebSocket("ws://139.224.107.180:60000");

        ws.onopen = function() {
            console.log("Connected to server");            
        };

      }

      function sendMessage() {
        if (!ws) {
          console.log("WebSocket对象不存在");
          console.log("请先连接服务器");
          return;
        }

        console.log("当前WebSocket状态:", ws.readyState);

        if (ws.readyState === WebSocket.OPEN) {
          const encoder = new TextEncoder();
          const data = encoder.encode("HelloWorld");
          ws.send(data);
          console.log("消息已发送");
        } else {
          console.log("连接未就绪，状态码:", ws.readyState);
          console.log("请先连接服务器");
        }
      }
    </script>
  </body>
</html>
